package com.weme.mine.activity

import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weme.common.activity.PhotoViewActivity
import com.weme.common.arouter.ARouterPaths
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.network.FEEDBACK_TIPS
import com.weme.common.util.*
import com.weme.common.view.BottomSelectionDialog
import com.weme.common.view.BottomSelectionListener
import com.weme.common.view.SelectionItem
import com.weme.common.view.SmoothImageView
import com.weme.mine.R
import com.weme.mine.bean.AlbumBean
import com.weme.mine.databinding.ActivityServiceBinding
import com.weme.mine.viewmode.ServiceViewMode
import dev.kratos.api.user_server.v1.FeedbackReply
import dev.kratos.api.user_server.v1.FeedbackRequest
import dev.kratos.api.user_server.v1.Media
import dev.kratos.api.user_server.v1.UploadAlbumRequest
import java.io.File

@Route(path = ARouterPaths.MINE_SERVICE_ACTIVITY)
class ServiceActivity : BaseMvvmActivity<ActivityServiceBinding, ServiceViewMode>() {

    val maxLength = 140
    private val uploader: AwsS3Uploader by lazy {
        AwsS3Uploader.getInstance(this)
    }
    private val albumList = mutableListOf<AlbumBean>()

    override fun initView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).titleBar(mBinding.customTopNavigationBar).init()
        mBinding.tvFeedbackTips.text = AppMkHelper.decodeString(FEEDBACK_TIPS)
        initRcv()
        mBinding.edService.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.length > maxLength) { // 如果输入字符数量超过最大限制，则截取前面的 MAX_CHARACTERS 个字符
                    val truncatedText = s.toString().substring(0, maxLength) // 更新输入框的文本
                    mBinding.edService.setText(truncatedText) // 将光标移动到文本末尾
                    mBinding.edService.setSelection(maxLength)
                    showToast(resources.getString(com.example.resources.R.string.live_max_characters_exceeded))

                }
            }

            override fun afterTextChanged(s: Editable) {
                mBinding.scvSubmit.alpha = if (mBinding.edService.text.toString().isNotEmpty()) 1F else 0.6F
            }
        })
        mBinding.scvSubmit.setOnFastClickListener {
            if (mBinding.scvSubmit.alpha == 1f) {
                val feedbackRequest = FeedbackRequest.newBuilder().setContent(mBinding.edService.text.toString().trim())
                albumList.forEachIndexed { index, albumBean ->
                    feedbackRequest.addImages(albumBean.imgUrl)
                }
                viewModel.putFeedBack(feedbackRequest.build())
            }
        }
     LiveEventBus.get<Any>(LiveConfig.NET_WORK_BLACK).observe(this) {
            if (it is FeedbackReply) {
                showToast(getString(com.example.resources.R.string.feed_back_service_success))
                finish()
            }
        }
    }

    private fun initRcv() {
        mBinding.rcvList.adapter = albumAdapter
        albumList.add(AlbumBean("", 0, 0, ""))
        albumList.add(AlbumBean("", 0, 0, ""))
        albumList.add(AlbumBean("", 0, 0, ""))
        albumAdapter.submitList(albumList)
    }


    private val albumAdapter = object : BaseQuickAdapter<AlbumBean, QuickViewHolder>() {

        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: AlbumBean?) {
            val simView = holder.getView<SmoothImageView>(R.id.simView)
            if (position == 0 && TextUtils.isEmpty(item!!.imgUrl)) {
                simView.setImageResource(com.example.resources.R.mipmap.icon_ed_info_album_add)
                simView.setOnClickListener {
                    showPhoto()
                }
            } else if (TextUtils.isEmpty(item!!.imgUrl)) {
                simView.setImageResource(com.example.resources.R.drawable.icon_album_null)
                simView.setRadius(0f)
            } else { //                Log.e("tag",item.type.toString())
                //                holder.setVisible(R.id.smvAvatar,item.type==7)
                simView.setRadius(18f)
                simView.loadImage(item.imgUrl)
                simView.setOnClickListener {
                    val intent = Intent(this@ServiceActivity, PhotoViewActivity::class.java)
                    intent.putExtra("url", item.imgUrl)
                    val options = ActivityOptions.makeSceneTransitionAnimation(this@ServiceActivity, it, "thumbnailTransition")
                    startActivity(intent, options.toBundle())
                }
            }


        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(R.layout.item_album, parent)
        }


    }


    fun showPhoto() {
        val selectionItems = listOf(
            SelectionItem(getString(com.example.resources.R.string.authentication_aboutme_camera), 0, object : BottomSelectionListener {
                override fun onTitleClicked(position: Int) {
                    MediaUtils.captureImage(this@ServiceActivity) {
                        uploadImage(it)
                    }
                }

            }),
            SelectionItem(getString(com.example.resources.R.string.authentication_aboutme_gellery), 1, object : BottomSelectionListener {
                override fun onTitleClicked(position: Int) {
                    MediaUtils.selectImages(this@ServiceActivity, 1) {
                        uploadImage(it)
                    }
                }

            }),
        )


        val btndialog = BottomSelectionDialog.newInstance(selectionItems)
        btndialog.show(this.supportFragmentManager,"")
    }

    fun uploadImage(imageUrl: String) {
        upDataAws(imageUrl, 1)
        val newAlbumBean = AlbumBean(imageUrl)

        if (TextUtils.isEmpty(albumList[albumList.size - 1].imgUrl)) {
            albumList.add(1, newAlbumBean)
            if (albumList[albumList.size - 1].imgUrl == "") {
                albumList.removeAt(albumList.size - 1)
            }
        } else if (albumList.size > 5) {
            albumList.removeAt(0)
            albumList.add(0, newAlbumBean)
        }

        albumAdapter.notifyDataSetChanged()

    }

    private fun upDataAws(imageUrl: String, type: Int) {

        uploader.setUploadListener(object : AwsS3Uploader.UploadListener {
            override fun onProgressChanged(progress: Int) {

            }

            override fun onUploadComplete(url: String) {
                val media = Media.newBuilder().setType(type).setUrl(url).build()

                val uploader = UploadAlbumRequest.newBuilder().addMedia(media).build()
                viewModel.uploaderApi(uploader)

            }

            override fun onUploadFailed() {

            }
        })
        uploader.uploadServiceImage(File(imageUrl))

    }

    override fun getViewModelClass(): Class<ServiceViewMode> = ServiceViewMode::class.java


}